const { exec } = require('../db/mysql')
const xss = require('xss')
const getList = async (author,keyword)=>{
    // 这里的1=1是为了 拼接sql语句，如果没有author和keyword，就不会有and，这样就会报错
    let sql = `select * from blogs where 1=1 `
    if(author){
        sql += `and author='${author}' `
    }
    if(keyword){
        sql += `and title like '%${keyword}%' `
    }
    sql += `order by createtime desc;`
    return await exec(sql)
    
}

const getDetail = async (id)=>{
    let sql = `select * from blogs where id='${id}'`
    const rows = await exec(sql)
    // 因为数据库返回就算是一个也是会返回数组，所以这里要取第一个，返回一个对象
    return rows[0]
}

const newBlog = async (blogdata = {})=>{
   blogdata.title = xss(blogdata.title)
   blogdata.content = xss(blogdata.content)
   let sql = `insert into blogs (title, content, createtime, author) values ('${blogdata.title}', '${blogdata.content}', '${new Date().getTime()}', '${blogdata.author}');`
   return await exec(sql).then(insertData=>{
       return {
           id:insertData.insertId
       }
   })
}

const updataBlog = async (id,blogdata = {})=>{
    let sql = `update blogs set title='${blogdata.title}', content='${blogdata.content}' where id=${id}`;
    return await exec(sql).then(updateData=>{
        if(updateData.affectedRows > 0){
            return true
        }
        return false
    })
}

const delBlog = async (id,author)=>{
    let sql = `delete from blogs where id=${id} and author='${author}'`;
    const deleteData = await exec(sql)
    if(deleteData.affectedRows > 0){
        return true
    }
    return false
}

module.exports = {
    getList,
    getDetail,
    newBlog,
    updataBlog,
    delBlog
}